package org.tony.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.tony.entity.DataCusomizedEntry;
import org.tony.entity.RelationDataSourceEntry;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 数据定制辅助类
 * @author tony
 *
 */
public class DataCustomizedUtil {
	
	private static final String FILE_PATH = "res/data-customized-relation.xml" ;
	private static final Boolean init = false ;
	private static DataCustomizedUtil instance = null ;
	
	private final Map<String,DataCusomizedEntry> dataCustomizedEntries = new HashMap<String,DataCusomizedEntry>();
	
	private DataCustomizedUtil(){
		init();
	}
	public static DataCustomizedUtil getInstance() {
		synchronized(init) {
			if(!init) {
				instance = new DataCustomizedUtil() ;
			}
		}
		return instance ;
	}

	/**
	 * 初始化
	 */
	private synchronized void  init() {
		try {
			Document doc = XmlDataSourceHelper.getDocuemnt(FILE_PATH);
			Element root = doc.getDocumentElement() ;
			NodeList relations = XmlDataSourceHelper.queryNodes("/data-cusomized-relations/relation", root);
			for(int i=0;i<relations.getLength();i++) {
				Node cur = relations.item(i);
				if(cur.getNodeType() == Node.ELEMENT_NODE) {
					DataCusomizedEntry entry = new DataCusomizedEntry() ;
					String id = XmlDataSourceHelper.queryNodes("@id", cur).item(0).getNodeValue();
					String tableName = XmlDataSourceHelper.queryNodes("@table", cur).item(0).getNodeValue();
					String relationKey = XmlDataSourceHelper.queryNodes("@relation_key", cur).item(0).getNodeValue();
					entry.setRelationId(id);
					entry.setTableName(tableName);
					entry.setRelationKey(relationKey);
					List<RelationDataSourceEntry> list = new ArrayList<RelationDataSourceEntry>();
					
					NodeList datasources = XmlDataSourceHelper.queryNodes("datasource", cur);
					for(int j=0;j<datasources.getLength();j++) {
						Node curD = datasources.item(j);
						if(curD.getNodeType() == Node.ELEMENT_NODE) {
							RelationDataSourceEntry rels = new RelationDataSourceEntry();
							String dsId= XmlDataSourceHelper.queryNodes("@from_ds", curD).item(0).getNodeValue();
							String fromTab = XmlDataSourceHelper.queryNodes("@from_tb", curD).item(0).getNodeValue();
							
							rels.setFromDateSourceId(dsId);
							rels.setFromTableName(fromTab);
							rels.setRelationKey(relationKey);
							NodeList columns = XmlDataSourceHelper.queryNodes("column", curD) ;
							Map<String,String> coloumsMap = new HashMap<String, String>();
							for(int k=0;k<columns.getLength();k++) {
								Node c = columns.item(k);
								if(c.getNodeType() == Node.ELEMENT_NODE) {
									String coloumName = XmlDataSourceHelper.queryNodes("@name", c).item(0).getNodeValue();
									String coloumType = XmlDataSourceHelper.queryNodes("@type", c).item(0).getNodeValue();
									coloumsMap.put(coloumName, coloumType);
								}
							}
							rels.setColumns(coloumsMap);
							list.add(rels);
						}
					}
					entry.setRelDts(list);
					dataCustomizedEntries.put(entry.getRelationId(), entry);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 写XML
	 * @param entry
	 * @return
	 */
	public synchronized boolean writeRelation(DataCusomizedEntry entry) {
		try {
			Document doc = XmlDataSourceHelper.getDocuemnt(FILE_PATH);
			Element root = doc.getDocumentElement();
			root.appendChild(entry.generateNode(doc));
			XmlDataSourceHelper.output(doc,FILE_PATH);
			dataCustomizedEntries.put(entry.getRelationId(),entry);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false ;
		}
	}
	
	/**
	 * 查找
	 * @param relationKey
	 * @param tableName
	 * @return
	 */
	public synchronized DataCusomizedEntry search(String relationKey,String tableName) {
		for(Iterator<DataCusomizedEntry> vIter = this.dataCustomizedEntries.values().iterator();vIter.hasNext();) {
			DataCusomizedEntry cur = vIter.next() ;
			if(cur.getRelationKey().equals(relationKey) && cur.getTableName().equals(tableName)) {
				return cur ;
			}
		}
		return null ;
	}
	
	public synchronized DataCusomizedEntry search(String relId) {
		return this.dataCustomizedEntries.get(relId);
	}
}
